<?php

namespace common\models;

use common\helpers\commonApi;
use Yii;

/**
 * This is the model class for table "{{%cart}}".
 *
 * @property int $id
 * @property int|null $userid 用户id
 * @property int|null $good_id 商品id
 * @property int|null $spec_id 规格id
 * @property int|null $campus_id 校区id
 * @property int|null $num 数量
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 */
class Cart extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%cart}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid', 'good_id', 'spec_id', 'campus_id', 'num'], 'integer'],
            [['create_time', 'update_time'], 'safe'],
            [['id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'userid' => '用户id',
            'good_id' => '商品id',
            'spec_id' => '规格id',
            'campus_id' => '校区id',
            'num' => '数量',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
        ];
    }

    /**
     * 加入购物成功
     * @param $userid
     * @param $good_id
     * @param $spec_id
     * @param $num
     * @param $campus_id
     * @return array
     */
    public function join($userid,$good_id,$spec_id,$num,$campus_id)
    {
        if (!$good_id||!$spec_id){
            return commonApi::message('请选择商品',false);
        }
        $model = GoodsSpec::find()->where(['good_id'=>$good_id,'id'=>$spec_id])->one();
        if (!$model){
            return commonApi::message('规格不存在',false);
        }
        $cart = self::find()->where(['userid'=>$userid,'spec_id'=>$spec_id,'campus_id'=>$campus_id])->one();
        if (!$cart){
            $cart = new self();
            $cart->userid = $userid;
            $cart->spec_id = $spec_id;
            $cart->campus_id = $campus_id;
            $cart->good_id = $good_id;
            $cart->num = 0;
        }
        $cart->num += $num;
        if ($cart->save()){
            return commonApi::message('加入成功');
        }
        return commonApi::message('加入失败',false);
    }

    /**
     * 购物车列表
     * @param $userid
     * @param $campus_id
     * @return array
     */
    public function getList($userid,$campus_id)
    {
        $data = self::find()
            ->alias('c')
            ->where(['c.userid' => $userid,'c.campus_id'=>$campus_id])
            ->select(['c.id as cart_id','c.num','c.spec_id','c.good_id as g_id','c.campus_id'])
            ->asArray()->all();
        $total_amount = 0;
        if (!$data){
            return commonApi::message('成功',true,['data'=>[],'total_amount'=>$total_amount]);
        }
        $model = new GoodsSpec();
        $amount = $model->calculation($data,1,0);
        if (!$amount['success']){
            return $amount;
        }
        $goods_spec = array_column($amount['data']['goods_spec'],null,'mark');
        foreach ($data as $k=>&$datum){
            $mark = $datum['g_id'].'_'.$datum['spec_id'];
            if (empty($goods_spec[$mark])){
                unset($data[$k]);
            }else{
                $datum['price'] = $goods_spec[$mark]['good_price'];
                $datum['spec_name'] = $goods_spec[$mark]['spec_name'];
                $datum['goods_name'] = $goods_spec[$mark]['good_name'];
                $datum['stock'] = (int)$goods_spec[$mark]['stock'];
                $datum['num'] = (int)$datum['num'];
                $datum['is_buy'] = $goods_spec[$mark]['is_buy'];
                $datum['main_img'] = commonApi::getDomain($goods_spec[$mark]['main_img']);
                $total_amount += $goods_spec[$mark]['pay_price'];
            }
        }
        return commonApi::message('成功',true,['data'=>array_values($data),'total_amount'=>$total_amount]);
    }

    /**
     * 数量加减
     * @param $cart_id 购物车id
     * @param $campus_id 校区
     * @param $type 类型 1：加 0：减
     * @return array
     */
    public function addSub($userid,$cart_id,$campus_id,$type)
    {
        $model = self::find()->where(['userid'=>$userid,'id'=>$cart_id,'campus_id'=>$campus_id])->one();
        if (!$model){
            return commonApi::message('商品不存在',false);
        }
        if ($type){//加
            $model->num +=1;
        }else{
            if ($model->num<=1){
                return commonApi::message('数量不能小于1',false);
            }
            $model->num -=1;
        }
        if ($model->save()){
            return commonApi::message('操作成功');
        }
        return commonApi::message('操作失败',false);
    }

    /**
     * 删除
     * @param $userid
     * @param $cart_id
     * @return array
     * @throws \yii\db\StaleObjectException
     */
    public function del($userid,$cart_id)
    {
        $res = self::deleteAll(['userid'=>$userid,'id'=>$cart_id]);
        if ($res){
            return commonApi::message('删除成功');
        }
        return commonApi::message('删除失败',false);
    }

    /**
     * 购物车数量
     * @param $userid
     * @param $campus_id
     * @return array
     */
    public function num($userid,$campus_id)
    {
        $count = self::find()
            ->alias('c')
            ->where(['c.userid' => $userid,'c.campus_id'=>$campus_id])
            ->count();
        return commonApi::message('ok',true,['count'=>$count]);
    }
}
